package cn.heycm.cachedrequest.filter;

import cn.heycm.cachedrequest.filter.wrapper.CachedRequestWrapper;
import cn.heycm.cachedrequest.filter.wrapper.CachedResponseWrapper;
import cn.heycm.cachedrequest.util.RequestUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@Order(Integer.MIN_VALUE)
public class RequestCacheFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (RequestUtil.isMultipart(request)) {
            filterChain.doFilter(request, response);
            return;
        }
        CachedRequestWrapper requestWrapper = new CachedRequestWrapper(request);
        CachedResponseWrapper responseWrapper = new CachedResponseWrapper(response);
        filterChain.doFilter(requestWrapper, responseWrapper);
        responseWrapper.writeToClient();
    }
}
